package navigation;

/**
 * Navigator that goes the shortest known path to the search-target
 *
 * Goes the shotest known path to the search-target.
 * Prefers to go south.
 *
 * @author hyurah
 */

public class GoShortestKnownPathNavigator extends Navigator{

	private PathQueue way = null;
	private SearchTarget searchTarget;

	/**
	 * Constructs an GoShortestKnownPathNavigator with data specified by the old navigator
	 *
	 * @param oldNavigator old navigator for data retrievel
	 */

	public GoShortestKnownPathNavigator(SearchTarget searchTarget, Navigator oldNavigator) {
		super(oldNavigator);
		this.searchTarget = searchTarget;
	}

	/**
	 * Decide direction to drive to next
	 *
	 * @return direction to drive to or -1 if destination is reached
	 * @throws IllegalMapStateException when search-target is not reachable in known map
	 */

	public int decideDirection() throws IllegalMapStateException {
		int direction;
		if(map.fieldIsExit(xPosition, yPosition)) {
			direction=-1;
		} else {
			if(way==null || way.size()==0) {
				way = Wayfinder.findShortestPath(searchTarget, map, xPosition, yPosition);
			}
			if(way.getPoint(0).getX()!=xPosition || way.getPoint(0).getY()!=yPosition) {
				way = Wayfinder.findShortestPath(searchTarget, map, xPosition, yPosition);
			}
			direction = (way.popPoint().getDirection()+4-facingDirection)%4;
		}
		return direction;
	}

}
